// pages/user/message-detail/message-detail.ts
import { getMsgDetails, msgLookDel } from '../../../api/user.js';
import { checkLogin } from '../../../libs/login';
import { goToPage, PAGE_LOGIN } from '../../../config/pages';

interface MessageItem {
  id: number;
  uid: number;
  mark: string;
  title: string;
  content: string;
  type: number;
  look: number;
  is_del: number;
  add_time: string;
  data: string;
}

interface MessageDataItem {
  key: string;
  label: string;
  value: string;
}

Page({
  data: {
    message: null as MessageItem | null,
    messageData: [] as MessageDataItem[],
    loading: true,
    messageId: 0
  },

  async onLoad(options: any) {
    // 检查登录状态
    if (!checkLogin()) {
      goToPage(PAGE_LOGIN, {}, 'reLaunch');
      return;
    }

    const { id } = options;
    if (id) {
      this.setData({ messageId: parseInt(id) });
      await this.loadMessageDetail();
    } else {
      this.setData({ loading: false });
    }
  },

  // 加载消息详情
  async loadMessageDetail() {
    if (!this.data.messageId) return;

    this.setData({ loading: true });

    try {
      // @ts-ignore
      const res = await getMsgDetails(this.data.messageId);
      
      if (res && res.data) {
        const message = res.data;
        this.setData({ 
          message,
          loading: false 
        });

        // 解析消息数据
        this.parseMessageData(message.data);
        
        console.log('消息详情加载成功:', message);
      } else {
        this.setData({ loading: false });
      }
    } catch (error: any) {
      console.error('加载消息详情失败:', error);
      this.setData({ loading: false });
      
      wx.showToast({
        title: error?.msg || '加载失败',
        icon: 'none',
        duration: 2000
      });
    }
  },

  // 解析消息数据
  parseMessageData(dataStr: string) {
    if (!dataStr) {
      this.setData({ messageData: [] });
      return;
    }

    try {
      const data = JSON.parse(dataStr);
      const messageData: MessageDataItem[] = [];
      
      // 根据不同的消息类型解析数据
      Object.keys(data).forEach(key => {
        const label = this.getDataLabel(key);
        const value = this.formatDataValue(key, data[key]);
        messageData.push({ key, label, value });
      });

      this.setData({ messageData });
    } catch (error) {
      console.error('解析消息数据失败:', error);
      this.setData({ messageData: [] });
    }
  },

  // 获取数据标签
  getDataLabel(key: string): string {
    const labelMap: { [key: string]: string } = {
      'order_id': '订单号',
      'pay_price': '支付金额',
      'store_name': '商品名称',
      'pay_time': '支付时间',
      'recharge_amount': '充值金额',
      'balance': '账户余额',
      'brokerage_amount': '佣金金额',
      'settle_time': '结算时间',
      'refund_amount': '退款金额',
      'refund_time': '退款时间',
      'bargain_price': '砍价金额',
      'combination_id': '拼团ID',
      'price_old': '原价格',
      'price_new': '新价格',
      'integral_amount': '积分变动',
      'balance_old': '原余额',
      'balance_new': '新余额'
    };
    
    return labelMap[key] || key;
  },

  // 格式化数据值
  formatDataValue(key: string, value: any): string {
    if (value === null || value === undefined) {
      return '暂无';
    }

    // 金额类型
    if (key.includes('price') || key.includes('amount') || key.includes('balance')) {
      return `¥${parseFloat(value).toFixed(2)}`;
    }

    // 时间类型
    if (key.includes('time')) {
      return new Date(value).toLocaleString();
    }

    return String(value);
  },

  // 删除消息
  async deleteMessage() {
    if (!this.data.message) return;

    wx.showModal({
      title: '确认删除',
      content: '确定要删除这条消息吗？',
      success: async (res) => {
        if (res.confirm) {
          try {
            // @ts-ignore
            const result = await msgLookDel({
              id: this.data.messageId,
              key: 'is_del',
              value: 1
            });
            
            if (result && result.code === 200) {
              wx.showToast({
                title: '删除成功',
                icon: 'success'
              });
              
              // 返回上一页
              setTimeout(() => {
                wx.navigateBack();
              }, 1500);
            }
          } catch (error: any) {
            console.error('删除消息失败:', error);
            wx.showToast({
              title: error?.msg || '删除失败',
              icon: 'none'
            });
          }
        }
      }
    });
  },

  // 返回上一页
  goBack() {
    wx.navigateBack();
  },

  // 根据消息类型获取图标
  getMessageIcon(mark: string): string {
    const iconMap: { [key: string]: string } = {
      'order_pay_success': 'fa-credit-card',
      'order_take': 'fa-check-circle',
      'order_refund': 'fa-undo',
      'recharge_success': 'fa-plus-circle',
      'user_extract': 'fa-money-bill-wave',
      'order_brokerage': 'fa-coins',
      'bargain_success': 'fa-handshake',
      'combination_success': 'fa-users',
      'price_revision': 'fa-tag',
      'integral_accout': 'fa-star',
      'user_balance_change': 'fa-wallet'
    };
    
    return iconMap[mark] || 'fa-bell';
  },

  // 格式化时间
  formatTime(timeStr: string): string {
    if (!timeStr) return '';
    
    const time = new Date(timeStr);
    return time.toLocaleString();
  }
});

